package masterjava.common.util;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: gkislin
 * Date: 7/26/11
 */
public class StringUtil {
    // Pattern for search ${key}
    // Keys must begin with letter ([a-zA-Z]) and contains any world cheracter (\w) or '.'
    static final Pattern REPLACE_PATTERN = Pattern.compile("\\x24\\x7B([a-zA-Z][\\w\\x2E].*?)\\x7D");
    static final Pattern WINDOWS_SLASH = Pattern.compile("\\\\");

    // replace in str ${key} to value
    public static String resolveReplacement(String str, Map<String, String> replacements) {
        Matcher matcher = REPLACE_PATTERN.matcher(str);
        while (matcher.find()) {
            String value = replacements.get(matcher.group(1));
            if (value != null) {
                str = matcher.replaceFirst(replaceWindowsSlash(value));
            }
        }
        return str;
    }

    public static String replaceWindowsSlash(String path){
         return WINDOWS_SLASH.matcher(path).replaceAll("/");
    }
}
